import { getStore, setStore } from "@/util/store";
import { getUserInfo, login } from "@/api/auth/login";
import website from "@/config/website.js";
const user = {
  state: {
    userInfo: {},
    permission: {},
    roles: [],
    token: getStore({ name: "token" }) || "",
  },
  actions: {
    //根据用户名登录
    LoginByUsername({ state }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            const data = res.data.data;
            state.token = data.token;
            setStore({ name: "token", content: data.token });
            state.tagList = [website.fistPage];
            setStore({ name: "tagList", content: state.tagList });
            resolve();
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    GetUserInfo({ commit }) {
      return new Promise((resolve) => {
        getUserInfo().then((res) => {
          commit("SET_USERINFO", res.data.data);
          resolve( res.data.data);
        });
      });
    },
    LogOut({ commit }) {
      return new Promise((resolve) => {
        localStorage.clear();
        resolve();
      });
    },
    //获取系统菜单
  },
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({ name: "userInfo", content: state.userInfo });
    },
    SET_PERMISSION: (state, permission) => {
      const result = permission.reduce((obj, item) => {
        if (item != null) {
          obj[item] = true;
        }
        return obj;
      }, {});
      state.permission = result;
    },
  },
};
export default user;
